// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  
  try {
    // 查询用户基本信息
    const userResult = await db.collection('users').where({
      _openid: openid
    }).get()
    
    if (userResult.data.length === 0) {
      return {
        success: false,
        message: '用户不存在',
        data: null
      }
    }
    
    const userInfo = userResult.data[0]
    
    // 查询用户统计数据
    const statsResult = await db.collection('user_stats').where({
      _openid: openid
    }).get()
    
    let stats = {
      works: 0,
      collections: 0,
      likes: 0
    }
    
    if (statsResult.data.length > 0) {
      stats = {
        works: statsResult.data[0].works || 0,
        collections: statsResult.data[0].collections || 0,
        likes: statsResult.data[0].likes || 0
      }
    }
    
    return {
      success: true,
      message: '获取用户信息成功',
      data: {
        userInfo,
        stats
      }
    }
  } catch (err) {
    return {
      success: false,
      message: '获取用户信息失败',
      error: err
    }
  }
} 